package pt.mauromad.guias.security;

import static pt.mauromad.guias.utils.CastUtils.cast;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

public class UserPrincipal {
	private final String domain;
	private final String username;
	private final String password;

	public UserPrincipal() {
		User user = cast(SecurityContextHolder.getContext().getAuthentication().getPrincipal());

		final String[] userContext = user.getUsername().split("\\\\");

		this.domain = userContext[0];
		this.username = userContext[1];
		this.password = user.getPassword();
	}

	public String getDomain() {
		return domain;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public boolean isAdministrator() {
		return hasRole("ROLE_ADMIN");
	}

	public boolean isCustomer() {
		return hasRole("ROLE_CUSTOMER");
	}

	private boolean hasRole(String roleName) {
		return SecurityContextHolder.getContext().getAuthentication().getAuthorities().contains(new SimpleGrantedAuthority(roleName));
	}

}
